package com.yb.web.shoper;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.yb.base.web.BaseAction;
import com.yb.bussiness.global.SystemLogService;
import com.yb.bussiness.global.SystemLogServiceImpl;
import com.yb.bussiness.goods.CategoryService;
import com.yb.bussiness.goods.CategoryServiceImpl;
import com.yb.bussiness.goods.TrMessageCommendService;
import com.yb.bussiness.goods.TrMessageCommendServiceImpl;
import com.yb.bussiness.information.InformationService;
import com.yb.bussiness.information.InformationServiceImpl;
import com.yb.bussiness.shoper.BrandService;
import com.yb.bussiness.shoper.BrandServiceImpl;
import com.yb.bussiness.shoper.ShoperMessageService;
import com.yb.bussiness.shoper.ShoperMessageServiceImpl;
import com.yb.domain.goods.ShoperMessage;
import com.yb.domain.goods.TgBrand;
import com.yb.domain.goods.TgCategory;
import com.yb.domain.goods.TgInformation;
import com.yb.domain.goods.TrMessageCommend;
import com.yb.domain.member.TsSysuser;
import com.yb.util.comm.Contants;
import com.yb.util.comm.RequestUtil;
import com.yb.util.framework.PageUtil;

/**
 * 
 * 商家信息管理 web 类
 */
public class ShoperMessageAction extends BaseAction {

	private ShoperMessageService service;
	private BrandService brandService;
	private ShoperMessage shopmessage;
	private int total;
	@SuppressWarnings("unchecked")
	private List rows;
	private String brandid;
	private InformationService infoservice;
	private TgInformation tgInformation = new TgInformation();
    private int flag;
    private String source;
	private TrMessageCommendService tmcService;
    private CategoryService catsrvice;
    private List<TgCategory> catrows;
    private List<TgCategory> pcatrows;
    private SystemLogService systemLogService;
    
	public ShoperMessageAction() {
		service = new ShoperMessageServiceImpl();
		brandService = new BrandServiceImpl();
		tmcService = new TrMessageCommendServiceImpl();
		infoservice = new InformationServiceImpl();
		catsrvice = new CategoryServiceImpl();
		systemLogService = new SystemLogServiceImpl();
	}

	/**
	 * 发布编辑信息
	 */
	public String addOrUpdateMessage() {
	    TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
            request, Contants.SESSION_USER);
	    String idStr = RequestUtil.getParam(request, "shopmessage.id", "");
		String shopId = RequestUtil.getParam(request, "shopId", "");
		if ("".equals(idStr)) {
			shopmessage.setCreatime(new Date());
			if ("".equals(shopId)) {
				shopmessage.setAutding("0");
			}

		}
		if (("1".equals(user.getType()) || "0".equals(user.getType()))&& !"".equals(shopId)) {
			shopmessage.setShoperId(Integer.parseInt(shopId));
			shopmessage.setAutding("1");
		} else {
			TgBrand brand = brandService.searchBySysId(user.getId().intValue());
			if (brand != null) {
				shopmessage.setShoperId(brand.getId().intValue());
			}
			//管理员分配的账号不需要审核
            if("1".equals(user.getSource())){
                shopmessage.setAutding("1");
            }
		}
       
		
		boolean isBoolean = service.isSaveOrUpdate(shopmessage);
		brandid = shopId;
		if (isBoolean) {
			 if(shopmessage.getId() == null)
				 systemLogService.saveSystemLog(request, "商家发布信息管理", "新增--"+brandService.findById(String.valueOf(shopmessage.getShoperId())).getName()+"--"+shopmessage.getTitle());
			 else
				 systemLogService.saveSystemLog(request, "商家发布信息管理", "修改--"+brandService.findById(String.valueOf(shopmessage.getShoperId())).getName()+"--"+shopmessage.getTitle());
			return "adminsuccess";
		}
		return "error";

	}

	/**
	 * 查询
	 * 
	 * @return
	 */
	public String search() {
		String type = RequestUtil.getParam(request, "type", "");
		String page = RequestUtil.getParam(request, "page", "");
		String row = RequestUtil.getParam(request, "rows", "");
		Map<String, String> parameMap = new HashMap<String, String>();
		parameMap.put("type", type);
		parameMap.put("page", page);
		parameMap.put("row", row);
		List<ShoperMessage> aclist = service.findByParameMap(parameMap);
		int count = service.count(parameMap);
		if (aclist != null) {
			total = count;
			rows = aclist;
		}
		return Contants.JSONSTRING_RESULT_NAME;

	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	public String deleteById() {
		PrintWriter out = null;
		try {

			out = response.getWriter();
			String idStr = RequestUtil.getParam(request, "ids", "");
			TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
					request, Contants.SESSION_USER);
			String[] delteid = idStr.split("_");
			try {
				for (int i = 0; i < delteid.length; i++) {
					systemLogService.saveSystemLog(request, "商家发布信息管理", "删除商家发布的信息--"+brandService.findById(String.valueOf(service.findById(delteid[i]).getShoperId())).getName());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			boolean isboolean = service.deleteById(idStr, user.getType());
			out.println("{result:" + isboolean + "}");
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 取消推荐
	 * 
	 * @return
	 */
	public String canceltuijian() {
		PrintWriter out = null;
		try {
			String id = RequestUtil.getParam(request, "id", "");
			shopmessage = service.findById(id);
			shopmessage.setRecommend("2");
			service.isSaveOrUpdate(shopmessage);
			boolean isboolean = infoservice.deleteByMessId(id);
			out = response.getWriter();
			out.println("{result:" + isboolean + "}");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 置顶/撤销置顶
	 * 
	 * @return
	 */
	public String changeIsTop() {
		String id = RequestUtil.getParam(request, "id", "");
		String isTop = RequestUtil.getParam(request, "isTop", "");
		String idString = RequestUtil.getParam(request, "idString", "");
		boolean isFlag = false;
		if (!"".equals(id))
			isFlag = service.changeIsTopById(id, isTop);
		else
			isFlag = service.changeTopByIdString(idString, isTop);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		if (isFlag)
			message = "操作成功";
		else
			message = "操作失败";
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");

		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {

			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询单个对象
	 */
	public String findMessageById() {
		String id = RequestUtil.getParam(request, "id", "");
		String see = RequestUtil.getParam(request, "see", "");
		ShoperMessage actObj = service.findById(id);
		if(!"".equals(source)){
		    flag = 1;
            tgInformation.setTitle(actObj.getTitle());
            tgInformation.setContent(actObj.getContent());
            tgInformation.setMessageId(new Integer(actObj.getId()+""));
		}
		//0热门活动资讯提取
		if("0".equals(source)){
		    return "tohotActivitiesInfo";
		}
		//1全站热点资讯提取
        if("1".equals(source)){
                List<TgCategory> cList = new ArrayList<TgCategory>();
                List<TgCategory> pList = catsrvice.findAll(1, 50);
                ActionContext.getContext().put("pid", "0");
                ActionContext.getContext().put("cid", "0");
                ActionContext.getContext().put("pList", pList);
                ActionContext.getContext().put("cList", cList);
                ActionContext.getContext().put("bid", id);
                
                catrows = catsrvice.findAll(1, 50);
            return "tohotinfo";
        }
        //2图文资讯提取
        if("2".equals(source)){
            return "toimginfo";
        }
        //3行业资讯提取
        if("3".equals(source)){
            List<TgCategory> pList = catsrvice.findAll(1, 50);
            ActionContext.getContext().put("pList", pList);
            ActionContext.getContext().put("pid", "0");
            return "toindustryinfo";
        }
		request.setAttribute("brandid", actObj.getShoperId());
		request.setAttribute("shopmessage", actObj);
		
		
		if (!"".equals(see) && "look".equals(see)) {
			return "adminlist";
		}
		TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);
		if ("2".equals(user.getType())) {
			return "modifBrand";
		}
		return "modif";
	}

	/**
	 * 查询单个对象
	 */
	public String toAddMessage() {
		TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);
		if ("2".endsWith(user.getType())) {
			return "modifBrand";
		}
		return "modif";
	}

	/**
	 * 审核
	 * 
	 * @return
	 */
	public String updateMessageById() {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			String idStr = RequestUtil.getParam(request, "id", "");
			String autding = RequestUtil.getParam(request, "autding", "");
			boolean isboolean = service.updateAutingId(idStr, autding);
			out.println("{result:" + isboolean + "}");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询
	 * 
	 * @return
	 */
	public String adminsearch() {
		String type = RequestUtil.getParam(request, "type", "");
		String page = RequestUtil.getParam(request, "page", "1");
		String row = RequestUtil.getParam(request, "rows", "10");
		String title = RequestUtil.getParam(request, "title", "");
		String auding = RequestUtil.getParam(request, "auding", "");
		String brandid = RequestUtil.getParam(request, "brandid", "");
		String name = RequestUtil.getParam(request, "name", "");
		Map<String, String> parameMap = new HashMap<String, String>();
		parameMap.put("type", type);
		parameMap.put("page", page);
		parameMap.put("row", row);
		parameMap.put("title", title);
		parameMap.put("auding", auding);
		parameMap.put("name", name);

		TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);

		parameMap.put("userType", user.getType());

		if ("".equals(brandid)) {
			TgBrand brand = brandService.searchBySysId(user.getId().intValue());
			brandid = brand.getId().toString();
			request.setAttribute("brandid", brandid);
		}
		parameMap.put("brandid", brandid);
		//提取资讯
		if(flag==1)parameMap.put("brandid", "");
		List<ShoperMessage> aclist = service.searchByParameMap(parameMap);

		List<ShoperMessage> newlist = new ArrayList<ShoperMessage>();
		if (aclist != null && !aclist.isEmpty()) {
			for (ShoperMessage shoperMessage : aclist) {
				TgInformation tgInformation = infoservice
						.readByMessId(shoperMessage.getId() + "");
				if (tgInformation != null) {
					// 3热门活动4热点资讯5资讯
					if ("1".equals(tgInformation.getHotActivities())) {
						shoperMessage.setRecommend("3");
					} else {
						if ("1".equals(tgInformation.getHot())) {
							shoperMessage.setRecommend("4");
						} else {
							shoperMessage.setRecommend("5");
						}
					}
				} else {
					shoperMessage.setRecommend("2");
				}
				newlist.add(shoperMessage);
			}
		}

		int count = service.searchByCount(parameMap);
		if (aclist != null) {
			total = count;
			rows = newlist;
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	/**
	 * 查询单个商家
	 */
	public String findshopMessageBybrandId() {
		TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);
		if ("2".endsWith(user.getType())) {
			TgBrand brand = brandService.searchBySysId(user.getId().intValue());
			if (brand != null) {
				request.setAttribute("brandid", brand.getId());
			}
			return "brandmessage";
		}
		//0热门活动资讯提取1全站热点资讯提取2图文资讯资讯提取
		String source = RequestUtil.getParam(request, "source", "");
		request.setAttribute("source", source);
		if(!"".equals(source)){
		    return "extractionshopMessage";
		}
		return "findshopMessageBybrandId";
	}

	public String findShopMessageById() {
		TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);
			TgBrand brand = brandService.searchBySysId(user.getId().intValue());
			if (brand != null) {
				request.setAttribute("tgBrand", brand);
			}
		return "findshopmessage";
	}

	public String messageCommend() {
		try {
			Long messageId = RequestUtil.getParam(request, "messageId", 0l);
			TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
					request, Contants.SESSION_USER);
			if (tmcService.checkMessage(user.getId(), messageId)) {
				response.getWriter().print("3");// 已推荐过
			} else {
				TrMessageCommend tmc = new TrMessageCommend();
				tmc.setMessageId(messageId);
				tmc.setUserId(user.getId());
				tmcService.save(tmc);
				response.getWriter().print("1");// 推荐成功
			}
		} catch (Exception e) {
			log.error("商家信息首页推荐错误", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
			}
		}
		return null;
	}

	public String messageCommandList() {
		try {
			int page = RequestUtil.getParam(request, "page", 1);
			int limit = RequestUtil.getParam(request, "rows", 20);
			PageUtil pu = service.findMessageCommendList(page, limit);
			rows = pu.getList();
			total = pu.getTotalRecords();
		} catch (Exception e) {
			log.error("显示商家信息推荐列表出错", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public ShoperMessageService getService() {
		return service;
	}

	public void setService(ShoperMessageService service) {
		this.service = service;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public List getRows() {
		return rows;
	}

	public void setRows(List rows) {
		this.rows = rows;
	}

	public ShoperMessage getShopmessage() {
		return shopmessage;
	}

	public void setShopmessage(ShoperMessage shopmessage) {
		this.shopmessage = shopmessage;
	}

	public String getBrandid() {
		return brandid;
	}

	public void setBrandid(String brandid) {
		this.brandid = brandid;
	}

    public TgInformation getTgInformation() {
        return tgInformation;
    }

    public void setTgInformation(TgInformation tgInformation) {
        this.tgInformation = tgInformation;
    }

    public int getFlag() {
        return flag;
    }

    public void setFlag(int flag) {
        this.flag = flag;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public List<TgCategory> getCatrows() {
        return catrows;
    }

    public void setCatrows(List<TgCategory> catrows) {
        this.catrows = catrows;
    }

    public List<TgCategory> getPcatrows() {
        return pcatrows;
    }

    public void setPcatrows(List<TgCategory> pcatrows) {
        this.pcatrows = pcatrows;
    }

}
